import base64

from django.http import JsonResponse
from rest_framework.views import APIView
from app01 import models
from app01.woutils import user_jwt
from app01.woutils.user_jwt import ParseToekn

# Create your views here.
from app01.woutils.encryption import aes_encrypt

from app01.models import UserInfo

#程序初次启动时创建管理员账号
def admin_user_create():
    dic = {
        "username": "admin",
        "password": base64.b64encode(aes_encrypt("admin".encode('utf-8'))).decode('utf-8')  ,
        "name": "管理员",
        "phone": "",
        "level": 10,
    }
    try:
        #检查初始管理账号是否存在
        ex = UserInfo.objects.filter(username="admin")
        if ex.exists():
            # print("主管理员账号已存在")
            return
        try:
            UserInfo.objects.create(**dic)
        except Exception as e:
            print("创建管理员账号失败",e)
    except Exception as e:
        pass

admin_user_create()

# def construct_search(model):
#     opts = model._meta
#     exclude = [f.name for f in opts.fields if getattr(f, 'choices')]
#     _fields = opts.fields
#     can_search_field_types = (models.CharField, models.CharField, models.IntegerField)
#     fields = []
#     for f in _fields:
#         if isinstance(f, can_search_field_types) and f.name not in exclude:
#             fields.append(f.name + '__icontains')
#     return fields


class AdminUser(APIView):
    '''用户信息管理'''
    def get(self,request):
        '''获取所有用户列表'''
        #获取页数参数
        try:
            page=int(request.query_params["page"])          #获取get请求传递的参数 page
            pagesize =int(request.query_params["pagesize"])
        except Exception as e:
            page = 1
            pagesize = 10
        if page < 1 :
            page = 1

        # search_fields = construct_search(UserInfo)
        # search = request.GET.get('search', None)
        # search_data = UserInfo.objects.all().order_by("id")
        # if search and search_fields:
        #     request.encoding = 'utf-8'
        #     search = search.strip()
        #     query_or = models.Q(*[(k, search) for k in search_fields], _connector='OR')
        #     search_data = search_data.filter(query_or).order_by("id")
        #     print(search_data)
        #获取搜索条件
        dic = {}
        username=request.query_params.get("username","")
        name=request.query_params.get("name","")
        phone=request.query_params.get("phone","")
        if username:
            dic['username__icontains'] = username    #username是需要搜索的字段名 __icontains为使用模糊搜索
        if name:
            dic['name__icontains'] = name
        if phone:
            dic['phone__icontains'] = phone
        #计算分页值
        #计算每一页显示内容的范围
        start_page = page * pagesize - pagesize
        end_page = page * pagesize

        #查询数据库 获取数据        .order_by('-id')是按id倒序进行排列
        datas = models.UserInfo.objects.filter(**dic).order_by('-id')[start_page:end_page].values()   #从数据库中提取数据
        datas_list=[]
        print(datas_list)
        #将数据中的密码消除   并转换为py的列表格式
        for item in datas:
            item["password"] = ""
            datas_list.append(item)
        #查询总数据条数
        total = models.UserInfo.objects.filter(**dic).count()

        #制作返回给前端的json
        data = {
            "code": 200,
            "msg": "查询成功",
            "total": total,
            "data": datas_list
        }
        return JsonResponse(data)          #以json格式返回数据
    def post(self,request):

        #提取前端提交的json参数
        username = request.data.get('username',"")
        password = request.data.get('password',"")
        name = request.data.get('name',"")
        phone = request.data.get('phone',"")
        level = request.data.get('level',"")

        #验证必须要有的参数是否填写
        if username == "":
            data = {'code': 503, "msg": "请填写账号", 'data': ""}
            return JsonResponse(data)
        if password == "":
            data = {'code': 503, "msg": "请输入密码", 'data': ""}
            return JsonResponse(data)
        # if name == "":
        #     data = {'code': 503, "msg": "请填写姓名", 'data': ""}
        #     return JsonResponse(data)

        #如果没有选择等级 默认为普通用户
        if level == "":
            level = 1

        #检测账号是否已存在
        ex=models.UserInfo.objects.filter(username=username)
        if ex.exists():
            data = {'code': 503, "msg": "账号已存在", 'data': ""}
            return JsonResponse(data)

        # 保存到数据库
        dic = {  # 将需要写入数据库的内容 构建为字典格式
            "username": username,
            "password": base64.b64encode(aes_encrypt(password.encode('utf-8'))).decode('utf-8'),
            "name": name,
            "phone": phone,
            "level": level,
        }

        try:
            models.UserInfo.objects.create(**dic)       #写入到数据库    传值时需要加**
        except Exception as e:
            data = {'code': 503, "msg": "新建用户失败", 'data': "用户名重复"}
            return JsonResponse(data)

        data = {'code': 200, "msg": "新建用户成功", 'data': ""}
        return JsonResponse(data)

    def delete(self,request):
        #提取出需要删除的用户id
        del_id=request.query_params.get("id")
        if del_id == "":
            data = {'code': 503,"msg":"需要删除的用户id为空", 'data':""}
            return JsonResponse(data)
        Obj=models.UserInfo.objects.filter(id=del_id)        #查询该id的数据是否存在
        if not Obj.exists():              #不存在的状态
            data = {'code': 503, "msg": "用户不存在", 'data': ""}
            return JsonResponse(data)
        Obj.delete()             #进行删除
        data = {'code': 200, "msg": "用户删除成功", 'data': ""}
        return JsonResponse(data)


    def put(self,request):
        '''改'''

        #获取必填值
        username = request.data.get("username","")
        name = request.data.get("name",""),

        #验证是否填写
        if name == "":
            data = {'code': 503, "msg": "请填写姓名", 'data': ""}
            return JsonResponse(data)
        if username == "":
            data = {'code': 503, "msg": "请填写账号", 'data': ""}
            return JsonResponse(data)

        #使用账号搜索账号信息
        data_obj = models.UserInfo.objects.filter(username=username)       #查询数据是否存在
        if data_obj.exists():                                      #如果账号存在
            dic = {}

            password =  request.data.get("password","")
            #查看是否更改了密码
            if password != "":
                #更改了密码,就将新密码加密后进行更新
                dic["password"] =base64.b64encode(aes_encrypt(password.encode('utf-8'))).decode('utf-8')

            #添加需要更新的字段
            dic['name'] =  request.data.get("name","")
            dic['phone'] = request.data.get("phone", "")
            dic['level'] = request.data.get("level", "")
            #进行更新操作
            data_obj.update(**dic)
            data = {
                "code": 200,
                "msg": "修改成功",
                "data": "修改成功"
            }
            return JsonResponse(data)
        else:
            data = {
                "code": 503,
                "msg": "数据不存在",
                "data": "数据不存在"
            }
            return JsonResponse(data)
        


class Update_password_api(APIView):
    def post(self,request):
        token = request.META.get('HTTP_AUTHORIZATION')  # 获取token
        token_dic, err = ParseToekn(token)
        datas=models.UserInfo.objects.get(username=token_dic['data']['username'])  #搜索用户信息

        old_pwd = request.data.get("old_pwd")  #旧密码
        new_pwd = request.data.get("new_pwd")  #新密码
        repeat_pwd= request.data.get("repeat_pwd")  #确认密码
        
        data = {
            "username":datas.username,
            "code": 200,
            "msg": "",
            "data": ""
        }
        if old_pwd == "":
            data['code'] = 503
            data['msg'] = "请输入旧密码"
            return JsonResponse(data)

        if new_pwd == "":
            data['code'] = 503
            data['msg'] = "请输入新密码"
            return JsonResponse(data)

        if repeat_pwd == "":
            data['code'] = 503
            data['msg'] = "请输入确认密码"
            return JsonResponse(data)

        if new_pwd != repeat_pwd:
            data['code'] = 503
            data['msg'] = "两次输入的密码不一致"
            return JsonResponse(data)

        # token = request.META.get('HTTP_AUTHORIZATION')  # 获取token
        # token_dic, err = ParseToekn(token)


        # datas=models.UserInfo.objects.get(username=token_dic['data']['username'])  #搜索用户信息

        password = base64.b64encode(aes_encrypt(old_pwd.encode('utf-8'))).decode('utf-8')
        if datas.password != password:  #对比旧密码是否正确
            data['code'] = 503
            data['msg'] = "旧密码错误"
            return JsonResponse(data)

        #设置新密码
        new_pwd = base64.b64encode(aes_encrypt(new_pwd.encode('utf-8'))).decode('utf-8')

        datas.password = new_pwd

        try:
            datas.save()
        except Exception as e:
            print(e)
            data['code'] = 503
            data['msg'] = "保存修改时出现错误"
            return JsonResponse(data)

        data['code'] = 200
        data['msg'] = "修改成功"
        return JsonResponse(data)